<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
    <title>inote 云记事</title>
    <link rel="stylesheet" type="text/css" href="../css/api.css"/>
    <link rel="stylesheet" type="text/css" href="../css/layout.css" />
    <link rel="stylesheet" type="text/css" href="../css/component/panel.css"/>
    <link rel="stylesheet" type="text/css" href="../css/component/bar.css" />
    <style>
    	html,body{
    		width: 100%;
            height: 100%;
    	}
        #wrap{
            height: 100%;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-flex-flow: column;
            width: 100%;
        }
        #header{
            position: fixed;
            z-index: 100;
        }
        #main{
            -webkit-box-flex: 1; 
            -webkit-flex: 1;  
            padding-top: 48px;
            z-index: 0;
        }
        .css-test{
            width: 50px;
            height: 50px;
            margin-top: 10px;
            background-color: #2196F3;
            border-radius: 100%;
        }
        .tabActive{
            background-color: #42A5F5;
        }
        .con{
            padding: 11px 8px 8px 8px;
            color: #212121;
        }
        .con-header{
            width: 100%;
            height: auto;
        }
        .ino-panel{
            margin-bottom: 12px;
        }
        .repeat{
            height: 24px;
            width: 60px;
            color: #fff;
            background-color: #2196F3;
            font-size: 16px;
            line-height: 24px;
        }
        .repeat > img{
            margin-bottom: -5px;
        }
        .pass{
            height: 24px;
            position: absolute;
            top: 59px;
            right: 8px;
            margin-left: 6px;
            color: #fff;
            background-color: #03A9F4;
            font-size: 16px;
            line-height: 24px;
        }
        .passNum{
            display: inline-block;
            text-align: center;
            border-radius: 5px;
            background-color: #fff;
            color: #E91E63;
            min-width: 14px;
            height: 24px;
            padding-left: 3px;
            padding-right: 3px;
        }
        .main{
            padding: 0px;
            height: auto;
            font-size: 16px;
            line-height: 24px;
        }
        .main-title,.main-list{
            /*padding: 15px;*/
            height: 54px;
        }
        .main-title{
            background-color: rgba(0, 0, 0, 0.12);
        }
        .main-list{
            position: relative;
        }
        .date{
            float: left;
            width: 90px;
            height: 54px;
            text-align: center;
        }
        .date > h4{
            font-weight: bold;
            font-size: 16px;
            margin: 0px;
            margin-top: 6px;
        }
        .date > span{
            font-size: 12px;
        }
        .detail{
            float: left;
            height: 54px;
            line-height: 54px;
            padding-left: 21px;
        }
        .more{
            position: absolute;
            top: 0px;
            right: 0px;
            padding: 15px;
        }
        .main-list{
            border-top: 1px solid rgba(0, 0, 0, 0.12);
        }
        .repeatHover{
            background-color: #64B5F6;
        }
        .passHover{
            background-color: #29B6F6;
        }
    </style>
</head>
<body>
    <div id="wrap">
        <div id="header" class="ino-bar home-bar">
            <div class="title">inote</div>
            <table class="ino-bar-content">
                <tr>
                    <td>
                        <div class="bar-tab bar-tab-back" tapmode="tabActive" onclick="api.closeWin();">
                            <img class="listTab" src="../image/png/webpage/arrow_back.png">
                        </div>                        
                    </td>
                    <td class="bar-right" align="right">
                        <div class="bar-tab bar-tab-menu" tapmode="tabActive" onclick="addSchedule()">
                            <img class="listTab" id="rightIcon">
                        </div>
                    </td>
                </tr>
            </table>
        </div>
        <div id="main">
            <div class="con">
                <div class="con-header">
                    <div class="ino-panel repeat" tapmode="repeatHover" onclick="openWebpage( '1' )">
                        <img src="../image/png/repeat.png" width="24"> 重复
                    </div>
                    <div class="ino-panel pass" tapmode="passHover" onclick="openWebpage( '2' )">
                        <span><strong class="passNum">0</strong></span> 过期任务
                    </div>
                </div>
                <div style="clear: both;"></div>
                <div class="con-main">
                    
                </div>
            </div>
        </div>
    </div>
</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/zepto.js"></script>
<script type="text/javascript">
    var winWidth = document.body.offsetWidth;
    var passWidth = winWidth - 142;
    $api.css($api.dom('.pass'), 'width:'+passWidth+'px;');
    // alert(winWidth);

    // =============================================
    // 打开webpage.html
    function openWebpage( index ) {
        switch (index)
        {
            case '1' :
                openWindow('repeat_schedule', '每日重复');
            break;
            case '2' :
                openPass('pass_schedule', '过期任务');
            break;
            default:
            break;
        }
    };
    function openPass(name, pagename) {
        // passSchedule
        api.openWin({
            name: 'pass_schedule',
            url: 'pass_schedule.html',
            pageParam: {
                name: name,
                pagename: pagename,
                taskId: '0',
                passdetail: passSchedule
            }
        });
    };
    function openWindow(name, pagename) {
        api.openWin({
            name: 'repeat_schedule',
            url: 'repeat_schedule.html',
            pageParam: {
                name: name,
                pagename: pagename,
                taskId: '0'
            }
        });
    };
    function openToast(msg) {
        api.toast({
            msg: msg,
            duration: 1500,
            location: 'middle'
        });
    };
	apiready = function(){
        var name = api.pageParam.name;
        changeBarTab();
        writePagename();

		var winWidth = api.winWidth;
        var db = api.require('db');
        db.openDatabase({
            name: 'inote',
            path: 'fs://inote.db'
        }, function(ret, err){
            if(ret.status){
                // 相关的操作放在这里
                sel('Schedule');
                closeDatabase();
            }
        });
        // =============================================
        // 打开inote.db
        // 插入新的数据，删除数据，修改数据,一次一条
        // 查询数据并读取出来，一次多条
        function closeDatabase() {
            db.closeDatabase({name:'inote'});     
        };
        function selectSql(sql) {
            db.selectSql({
                name:'inote',
                sql: sql
            }, function(ret, err){
                if(ret.status){
                    var datas = ret.data;
                    if (datas.length === 0) {
                        // alert('快添加任务吧');
                        openToast('快添加任务吧');
                        // 这里添加提示框
                    }else{
                        // alert( JSON.stringify( ret ) );
                        getSingleData(datas);
                        // 日期进行升序排序
                        dateGroup.sort(function(a,b){return a-b});
                        // alert(districtArray(dateGroup));
                        writeTaskTitle(districtArray(dateGroup));
                        addTimeStamp(schedule);
                        // 渲染
                        schedule.sort(function(a,b){return a[7]-b[7]});
                        for (var i = 0; i < schedule.length; i++) {
                            writeListTask(schedule[i]);
                        };
                        // 分出过期的任务
                        addTimeStamp(passSchedule);
                        passSchedule.sort(function(a,b){return a[7]-b[7]});
                        var passNum = passSchedule.length;
                        $api.dom('.passNum').innerHTML = passNum;
                        // alert(passSchedule);
                        // 为数组增加时间戳
                    };
                }
            });
        };
        // =============================================
        // 具体db的操作
        // @table, @id, @type, @detail
        function sel(table) {
            var sql = "SELECT * FROM "+table+" WHERE type = '0'";
            selectSql(sql);
        };
	};

    // var datas = new
    var schedule = new Array();
    var dateGroup = new Array();
    var passSchedule = new Array();
    // @schedule保存所有的分组数据
    // @dateGroup保存分组名
    
    function addTimeStamp(arr) {
        for (var i = 0; i < arr.length; i++) {
            var timestamp = arr[i][5].replace(/(-)|(\s)|(:)/g, "");
            // var timestamp = (new Date(arr[i][4])).valueOf().toString();
            // 字符替换或者Date时间戳，后进行排序
            arr[i].push(timestamp);
            // alert(arr[i]);
        };
        return arr;
    };
    // ========================================================
    // 获得今天的日期
    function getTodayDate() {
        var nowDate = new Date();
        var today = nowDate.getFullYear().toString(),
            theMonth = (nowDate.getMonth() + 1).toString(),
            theDay = nowDate.getDate().toString(),
            Month,
            Day;
        if (theMonth.length === 1) {
            Month = theMonth;
        }else{
            Month = '0'+theMonth;
        }
        if (theDay.length === 1) {
            Day = theDay;
        }else{
            Day = '0'+theDay;
        }
        var nowDateString = today+Month+Day;
        return nowDateString;
    };
    function getAllTodayDate() {
        var nowDate = new Date();
        var today = nowDate.getFullYear().toString(),
            theMonth = (nowDate.getMonth() + 1).toString(),
            theDay = nowDate.getDate().toString(),
            theHour = nowDate.getHours().toString(),
            theMinute = nowDate.getMinutes().toString(),
            Month,Day,Hour,Minute;

        if (theMonth.length === 2) {
            Month = theMonth;
        }else{
            Month = '0'+theMonth;
        }
        if (theDay.length === 2) {
            Day = theDay;
        }else{
            Day = '0'+theDay;
        }
        if (theHour.length === 2) {
            Hour = theHour;
        }else{
            Hour = '0'+theHour;
        }
        if (theMinute.length === 2) {
            Minute = theMinute;
        }else{
            Minute = '0'+theMinute;
        }
        var nowDateString = today+Month+Day+Hour+Minute;
        return nowDateString;
    };
    function getSingleData(datas) {
        for (var i = 0; i < datas.length; i++) {
            // datas[i].id
            var schedule_datas = new Array();
            schedule_datas[0] = datas[i].id;
            schedule_datas[1] = datas[i].type;
            schedule_datas[2] = datas[i].status;
            schedule_datas[3] = datas[i].title;
            schedule_datas[4] = datas[i].detail;
            schedule_datas[5] = datas[i].startTime;
            schedule_datas[6] = datas[i].endTime;
            
            var sdate = datas[i].startTime.substr(0, 10).replace(/-/g, "");
            // 判断任务是否过期
            var edateInt = datas[i].endTime.replace(/(-)|(\s)|(:)/g, "");
            if (edateInt >= getAllTodayDate()) {
                // 没过期的任务
                // alert(getAllTodayDate());
                dateGroup.push(sdate);
                schedule.push(schedule_datas);
            }else{
                // 过期的任务
                passSchedule.push(schedule_datas);
            };
        };
    };
    
    function checkDateGroup(checkVal) {
        for (var i = 0; i < dateGroup.length; i++) {
            if (dateGroup[i] === checkVal) {
                return true;
            }else{
                return false;
            };
        }
    };
    // 过滤数组的重复值
    function districtArray(array){ 
        var result = new Array(); 
        for(var i in array){ 
            if(result.indexOf(array[i]) == -1){ 
                result.push(array[i]); 
            } 
        } 
        return result; 
    };
    
    // 写入一天内时间的标题
    function writeTaskTitle(dateGroup) {
        for (var i = 0; i < dateGroup.length; i++) {
            if (dateGroup[i] === getTodayDate()) {
                var thisDate = getTodayDate().slice(0,4)+'-'+getTodayDate().slice(4,6)+'-'+getTodayDate().slice(6,8);
                var thisDay = '今天';
            }else{
                var thisDate = dateGroup[i].slice(0,4)+'-'+dateGroup[i].slice(4,6);
                var thisDay = dateGroup[i].slice(6,8)+"日";
            };
            var todayTaskTitle = '<div class="ino-panel main" id="task'+dateGroup[i]+'"><div class="main-title"><div class="date"><h4>'+thisDay+'</h4><span>'+thisDate+'</span></div><div class="detail"><strong id="sum'+dateGroup[i]+'"></strong>件计划任务</div></div></div>';
            $api.append($api.dom('.con-main'), todayTaskTitle);
        }
    };
    // 插入具体数据
    function writeListTask(datas) {
        var mainId = '#task'+datas[7].substr(0, 8);
        var listId = 'list'+datas[7].substr(0, 8);
        var dayMoment = timeBucket(datas[5]);
        var thisTitle = datas[3];
        var thisTime = timeExtent(datas[5], datas[6]);
        var status = 'chevron_right';
        if (datas[2] === '1') {
            var status = 'check';
        };

        var tistTask = '<div class="main-list" id="'+listId+'" onclick="openDetailPage('+datas[0]+')"><div class="date"><h4>'+dayMoment+'</h4><span>'+thisTime+'</span></div><div class="detail">'+thisTitle+'</div><div class="more"><img src="../image/png/'+status+'.png" width="24"></div></div>';
        $api.append($api.dom(mainId), tistTask);
        sumTask(listId);
    };
    // 计算当天的任务数量并且写入标题栏
    var checkSumTask;
    var allList = 0;
    function sumTask(listId) {
        
        if (listId === checkSumTask) {
            allList = allList+1;
            $api.dom('#sum'+listId.substr(4, 12)).innerHTML = allList;
            // alert(allList);
        }else{
            checkSumTask = listId;
            allList = 1;
            $api.dom('#sum'+listId.substr(4, 12)).innerHTML = allList;
            // alert(allList);
        }
    };
    // 计算时间差
    function timeExtent(s, e) {
        var st = s.substr(11, 5);
        var et = e.substr(11, 5);
        return st+'-'+et;
    };
    // 划分时间段
    function timeBucket(s) {
        var st = parseInt(s.substr(11, 2));
        if (st >= 6 && st <= 8) {
            return '早上';
        }else if (st > 8 && st <= 11){
            return '上午';
        }else if (st > 11 && st <= 14){
            return '中午';
        }else if (st > 14 && st <= 17){
            return '下午';
        }else{
            return '晚上';
        }
    };

    // 打开任务的详情页
    function openDetailPage(id) {
        api.openWin({
            name: 'add_schedule',
            url: 'add_schedule.html',
            pageParam: {
                name: 'detailPage',
                pagename: '任务详情',
                taskId: id
            }
        });
        // alert(id);
    };  
    // =====================================================
    // =====================================================
    // 添加标题
    function writePagename() {
        var pagename = api.pageParam.pagename;
        $api.dom('.title').innerHTML = pagename;
    };

    // =====================================================
    // 改变菜单按钮
    function changeBarTab() {
        var name = api.pageParam.name;
        changeClass(1, 'add');
    };

    // =====================================================
    // @name的值有：more_vert, send, check, find
    function changeClass(index, name) {
        var rightTab = $api.dom('.bar-right');
        var rightIcon = $api.dom('#rightIcon');
        if (index === 0) {
            $api.css(rightTab, 'display: none;');
        }else{
            $api.attr(rightIcon, 'src', '../image/png/webpage/'+ name +'.png');
            // src="../image/png/webpage/more_vert.png"
        };
    };

    // =====================================================
    function addSchedule() {
        api.openWin({
            name: 'add_schedule',
            url: 'add_schedule.html',
            pageParam: {
                name: 'add_schedule',
                pagename: '添加新任务',
                taskId: '0'
            }
        });
    };
</script>
</html>